;
(function(window, jQuery){
	window.elmBody = window.elmBody || jQuery('body');
	window.elmWin = window.elmWin || jQuery(window);
	window.elmDocElement = window.elmDocElement || jQuery(document.documentElement);

	var Support = {
		/**
		 * 追加一个POST表单，用于单行内容内的操作
		 * @param pStrUrl {String}
		 * @param pElmBody {jQuery}
		 * @param pParameters {JSON}
		 */
		appendForm: function(pStrUrl, pElmBody, pParameters){
			var elmForm = jQuery('<form action="'+pStrUrl+'" method="POST"></form>');
			elmForm.append('<input type="hidden" name="__t" value="'+(new Date()).getTime()+'" />');
			for(var key in pParameters){
				if( pParameters.hasOwnProperty(key))
					elmForm.append('<input type="hidden" name="'+key+'" value="'+pParameters[key]+'" />');
			}
			pElmBody.append(elmForm);
			return elmForm;
		}
	};

	var EditInPlace = {
		onEditCommand: function(pElmEditButton){
			var elmSaveButton = jQuery('<span class="button button-positive">保存</span>'),
				elmCancelButton = jQuery('<span class="button button-ordinary">取消</span>'),
				elmRow = pElmEditButton.parents('tr');
			jQuery.each(elmRow.find('[role="field"]'), function(idx, field){
				var elmField = jQuery(field);
				elmField.after('<input type="text" name="'+elmField.attr('data-name')+'" value="'+elmField.text()+'"/>');
				elmField.remove();
			});
			pElmEditButton.after(elmCancelButton);
			pElmEditButton.after(elmSaveButton);
			pElmEditButton.hide();
		}
	};

	var sortName = {
			'desc': '降序',
			'asc': '升序'
		},
		EVT_NS = 'DATA_LIST';

	var DataList = function(elmDataOutput, settings){
		var options = {
			onBeforeQuerySubmit: function(){ return true; },
			onAfterQuerySubmit: function(){}
		};
		jQuery.extend(options, settings);
		this.options = options;
		this.elmDataOutput = elmDataOutput;
		this.elmQueryForm = elmDataOutput.find('[role="queryForm"]');
		this.elmQuerySubmit = elmDataOutput.find('[role="querySubmit"]');
		this.elmDataList = elmDataOutput.find('[role="dataList"]');
		this.elmPagination = elmDataOutput.find('[role="pagination"]');
		this.elmTbody = this.elmDataList.find('tbody');
		this.elmThead = this.elmDataList.find('thead');
		this.elmWrapper = this.elmDataList.parent();
		this.strScrollerId = 'DoubleScrollReal_' + (new Date()).getTime();
		this.elmScroll = jQuery('<div id="'+this.strScrollerId+'" style="height:17px;overflow-x:scroll;overflow-y:hidden;"><div style="height:50px;"></div></div>');
		this.elmScrollContent = this.elmScroll.find('div');
		var me = this;
		// 默认初始化功能
		// 拉伸表格
		this.stretchTable();
		elmWin.on('resize.'+EVT_NS, function(){ me.stretchTable()});
		// 删除关键字
		this.keywordsRemove();
		// 表单查询
		this.queryForm();
		// 分页
		if( this.elmPagination ) this.pagination();
		// 删除记录
		this.deleteRecord();
		// 列表中的弹窗输入提示
		this.prompt();

		this.popupAdvConditions();
	};

	DataList.prototype = {
		/*拉伸表格宽度*/
		stretchTable: function(){
			var jqDataTable = this.elmDataList;
			var jqWrapper = this.elmWrapper;
			var strStretchClass = 'fullWidth';
			var tableWidth = jqDataTable.width();
			var wrapperWidth = jqWrapper.width();
			var me = this;
			if( tableWidth > wrapperWidth ) {
				jqWrapper.removeClass(strStretchClass);
				this.doubleScroll();
			}else{
				jqWrapper.addClass(strStretchClass);
				this.singleScroll();
			}

		},
		/*上下双滚动条*/
		doubleScroll: function(){
			var jqDataTable = this.elmDataList;
			var jqWrapper = this.elmWrapper;
			var domWrapper = jqWrapper.get(0);
			var wrapperWidth = jqWrapper.width();
			var dataTableWidth = jqDataTable.width();
			this.elmScroll.show();
			this.elmScroll.width(wrapperWidth);
			this.elmScrollContent.width(dataTableWidth);
			jqWrapper.before(this.elmScroll);
			var jqReal = jQuery('#'+this.strScrollerId);
			var domReal = jqReal.get(0);
			jqWrapper.on('scroll', function () {
				domReal.scrollLeft = domWrapper.scrollLeft;
			});
			jqReal.on('scroll', function () {
				domWrapper.scrollLeft = domReal.scrollLeft;
			});
		},
		singleScroll: function(){
			this.elmScroll.hide();
		},
		/*隔行换色（IE8-）*/
		zebraLists: function(){
			if( window.attachEvent){
				var jqDataTable = this.elmDataList;
				jqDataTable.find('tr:even').addClass('even');
			}
		},
		/*表格可点击效果*/
		selectable: function(){
			var jqTbody = this.elmTbody,
				jqDataTable = this.elmDataList,
				jqSelected = null;
			jqTbody.find('tr').on('click', function(){
				var jqCurrTr = jQuery(this);
				if( jqCurrTr.hasClass('selected') ) return;
				if( jqSelected ) jqSelected.removeClass('selected');
				jqCurrTr.addClass('selected');
				jqSelected = jqCurrTr;
			});
		},
		/*复选框全选*/
		toggleCheckbox: function(){
			var jqDataTable = this.elmDataList;
			var jqCtrlAll = jqDataTable.find('thead :checkbox');
			var jqCkbs = jqDataTable.find('tbody :checkbox');
			var max = jqCkbs.length;
			jqCtrlAll.on('click', function(){
				var status = jqCtrlAll.prop('checked');
				jqCkbs.prop('checked',status);
			});
			jqCkbs.on('click', function(){
				var num = jqCkbs.filter(':checked').length;
				if( num == 0){
					jqCtrlAll.prop('checked', false);
				}else if( num == max ){
					jqCtrlAll.prop('checked', true);
				}
			});
		},
		/*下拉菜单翻页*/
		pageSelect: function(jqPageSelector){
			jqPageSelector.on('change', function(){
				var strSearch = Tool.setParameter('page_num', parseInt(jqPageSelector.val(), 10));
				window.location.search = strSearch;
			});
		},
		/*表头排序*/
		sortable: function(){
			jQuery.each(this.elmThead.find('th'), function(index, th){
				var jqTh = jQuery(th);
				var paramOrder = Tool.getQuery('order'); // 参数中的排序顺序
				var paramBy = Tool.getQuery('by'); // 参数中的排序字段
				var strColData = jqTh.attr('data-coldata') || '{}'; // 存储在表头单元格中的数据，包含当前列字段
				strColData = strColData.replace(/'/g, '"');
				var colData = jQuery.parseJSON(strColData);
				var jqSortIco = jQuery('<b class="sort"></b>');
				if( colData.func != 'sort' ) return;
				// 将排序样式添加到页面
				jqTh.addClass('sortable');
				// 寻找排序字段，添加排序顺序
				jqTh.find('span').append(jqSortIco);
				if( paramBy == colData.by ) jqSortIco.addClass(paramOrder);
				// 绑定表头点击事件
				var jqTip;
				var order = 'desc'; // 默认排序规则
				jqTh.on('click', function(evt){
					evt.preventDefault();
					// 检测是否需要反向排序
					if( paramOrder ){
						if( paramBy == colData.by)
							paramOrder == 'desc' ? order = 'asc' : order = 'desc';
					}
					window.location.search = Tool.setSearch(window.location.search, {order: order, by:colData.by});
				});
				// 悬停时添加说明文字
				var offsetLeft = 0;
				jqTh.hover(function(evt){
					// 检测是否需要反向排序
					if( paramOrder ){
						if( paramBy == colData.by)
							paramOrder == 'desc' ? order = 'asc' : order = 'desc';
					}
					jqTip = jQuery('<div style="padding:5px 10px;border:1px solid black;background:#fff;position:absolute;">按“' + jqTh.text() + '”' + sortName[order] + '排列</div>');
					elmBody.append(jqTip);
					offsetLeft = jqTip.outerWidth()/2;
					jqTip.css({
						left: evt.clientX - offsetLeft,
						top: evt.clientY + 20
					});
				}, function(evt){
					if( !jqTip ) return;
					jqTip.remove();
					jqTip = null;
				})
					.on('mousemove', function(evt){
						if( !jqTip ) return;
						jqTip.css({
							left: evt.clientX - offsetLeft,
							top: evt.clientY + 20
						});
					});
			});
		},
		/*固定头部*/
		fixedHeader: function(){
			if(!window.XMLHttpRequest) return;
			var jqThead = this.elmThead,
				jqWrapper = this.elmWrapper,
				jqScrollTop = this.elmScroll,
				jqCloneThead = jqThead.clone(),
				jqCloneSpan = jqCloneThead.find('span');
			jQuery.each(jqThead.find('span'), function(index, elmSpan){
				jqCloneSpan.eq(index).width(elmSpan.scrollWidth);
			});
			var jqTmpTable = jQuery('<div class="cmpt-data-output-list hide"><table><thead></thead></table></div>'),
				elmTmpTable = jqTmpTable.get(0);
			jqTmpTable.find('thead').append(jqCloneThead);
			jqTmpTable.css({
				position:'fixed',
				overflow:'hidden',
				width: jqWrapper.width(),
				top:0
			});

			var hasScrollTop = false,// 是否有顶部的滚动条
				jqReal = jQuery('#'+this.strScrollerId),
				elmWrapper = jqWrapper.get(0),
				elmReal = jqReal.get(0);
			if(jqReal.length>0) {
				hasScrollTop = true;
				// 为新增的克隆头部添加滚动事件
				jqWrapper.on('scroll', function () {
					elmTmpTable.scrollLeft = elmWrapper.scrollLeft;
				});
				jqReal.on('scroll', function () {
					elmTmpTable.scrollLeft = elmReal.scrollLeft;
				});
			}
			var intFixedTop = jqThead.offset().top,
				docElm = document.documentElement,
				isFixed = false; // 为了只触发一次
			elmWin.on('scroll.'+EVT_NS, function(){
				if( docElm.scrollTop >= intFixedTop && !isFixed){
					// 开始固定
					isFixed = true;
					elmBody.append(jqTmpTable);
					if( hasScrollTop ) {
						jqScrollTop.css({
							'position':'fixed',
							'top':0
						});
						jqTmpTable.css({
							top: jqScrollTop.height() + 'px'
						});
					}
					jqTmpTable.removeClass('hide').css('left',jqWrapper.offset().left);
				}else if(docElm.scrollTop < intFixedTop && isFixed){
					// 解除固定
					isFixed = false;
					if( hasScrollTop ) {
						jqScrollTop.css('position', 'static');
					}
					jqTmpTable.addClass('hide');
				}
			});
		},
		/**
		 * 提交查询表单
		 */
		queryForm: function(){
			var elmQueryForm = this.elmQueryForm;
			var me = this;
			this.elmQuerySubmit.on('click', function(){
				if( !me.options.onBeforeQuerySubmit() ) return;
				// 保证强制刷新的机制，添加一个随机数
				var elmT = elmQueryForm.find('[name="__t"]');
				if(elmT.length == 0 ){
					elmT = jQuery('<input type="hidden" name="__t" />');
					elmQueryForm.append(elmT);
				}
				elmT.val((new Date()).getTime());
				PreloadingPage.beginLoad();
				elmQueryForm.submit();
				me.options.onAfterQuerySubmit();
			});
		},
		/**
		 * 删除关键字
		 * 点击x号，查找表单中相关字段，删除之，然后重新提交搜索表单
		 * 查询表单QueryForm中必须把高级查询得来所有字段都做成类型为hidden的表单域
		 */
		keywordsRemove: function(){
			var elmQueryForm = this.elmQueryForm;
			this.elmDataOutput.on('click', '[role="removeKeyword"]', function(){
				PreloadingPage.beginLoad();
				var oParameters = {};
				oParameters[jQuery(this).attr('data-name')] = '';
				oParameters['__t'] = new Date().getTime();
				window.location.search = Tool.setParameter(oParameters);
			});
		},
		/**
		 * 分页按钮
		 */
		pagination: function(){
			this.elmPagination.find('a').on('click', function(event){
				if( jQuery(this).attr('href') ){
					PreloadingPage.beginLoad();
					return true;
				}else event.preventDefault();
			});
			this.elmPagination.find('select').on('change', function(){
				PreloadingPage.beginLoad();
				window.location.search = Tool.setParameter('page_num', jQuery(this).val());
			});
		},
		/**
		 * 删除一条记录
		 * 数据表中role="delete"的按钮会被标记为删除按钮
		 * HTML:
		 * <span role="delete" data-id="01" data-url="/server/post.php" data-text="迈特">删除</span>
		 * role="delete"    被标记为该按钮进行删除操作
		 * data-id="01"    要删除的记录的id，作为提交参数的一部分，也可能用于构造提示文本
		 * data-url="/server/post.php"    向该地址提交删除操作
		 * data-text="迈特"    提示文本，可选项，点击删除操作将弹出“是否删除迈特”，如果未填写，将使用id作为提示文本
		 */
		deleteRecord: function(){
			this.elmDataList.on('click', '[role="delete"]', function(){
				var elmButton = jQuery(this),
					strId = elmButton.attr('data-id'),
					strUrl = elmButton.attr('data-url'),
					strMsg = elmButton.attr('data-msg') || strId;
				if( window.confirm('确定删除'+strMsg+'？') ){
					var elmDeleteForm = Support.appendForm(strUrl, elmBody, {id: strId});
					PreloadingPage.beginLoad();
					elmDeleteForm.submit();
				}
			});
		},
		/**
		 * 弹窗输入并提交
		 * 点击时弹出window.prompt窗口，提示输入内容后提交表单
		 */
		prompt: function(){
			this.elmDataList.on('click', '[role="prompt"]', function(){
				var elmButton = jQuery(this),
					strId = elmButton.attr('data-id'),
					strUrl = elmButton.attr('data-url'),
					strMsg = elmButton.attr('data-msg');
				var promptInput = window.prompt(strMsg, '');
				if( promptInput != null ){
					promptInput = jQuery.trim(promptInput);
					if( promptInput.length > 0 ){
						// 有实际内容，提交
						var elmPostForm = Support.appendForm(strUrl, elmBody, {id:strId, prompt:promptInput});
						PreloadingPage.beginLoad();
						elmPostForm.submit();
					}else{
						alert('您未输入任何内容！');
					}
				}
			});
		},
		/**
		 * 高级条件查询窗口
		 */
		popupAdvConditions: function(){
			// 高级过查询条件
			this.elmDataOutput.on('click', '[role="advConditions"]', function(){
				window.parent.openIfmDialog('所有条件', jQuery(this).attr('data-url'));
			});
		},
		editInPlace: function(){
			this.elmDataList.on('click', '[role="editInPlace"]', function(){
				EditInPlace.onEditCommand(jQuery(this));
			});
		}
	};
	DataList.prototype.constructor = DataList;
	window.DataList = DataList;
})(window, jQuery);